
    var isSchedulerVisible=false;

    var ErrorMessages = {
        CANNOT_USE_EXACT_DATES :    "Recurring reports cannot use Exact Dates on the Parameters Tab. Please enter Calculated dates before saving the report.",
        REP_NAME_EXISTS:            "Report name is empty or already exists. Please choose a different report name.",
        VALIDATION_ERROR:           "Error during validating parameters.",
        SCH_DATE_EMPTY:             "Error: Scheduled Date is empty. Please enter a date.",
        SCH_TIME_EMPTY:             "Error: Scheduled Time is empty. Please enter a time.",
        SCH_DATE_INVALID:           "Error: Scheduled Date is invalid. Please enter a valid date.",
        SCH_TIME_INVALID:           "Error: Scheduled Time is invalid. Please enter a valid time.",
        SCH_TIME_BEFORE_CURRENT:    "Error: Scheduled time is before the current time. Please enter a time that is after the current time.",
        SCH_DATE_BEFORE_TODAY:      "Error: Scheduled date is before today. Please enter a date that is after today.",
        DELETE_CONFIRM:             "Are you sure you want to delete selected report?"
    };

    var TabParams = {
        setDerivedParams : function($elem){
            var $elemInput = $elem.parents("div.input");
            $elemInput.find("input[type=hidden]").val(
                $elemInput.find("select.interval").val()+"_"+
                $elemInput.find("input.quantity").val()+"_"+
                $elemInput.find("select.boundary").val()
            );
        },

        setDescription : function(desc){
            var $repParamDesc = $("#report_parameter_description");
            if (desc!=undefined){
                $repParamDesc.html(desc);
            }else{
                $repParamDesc.html("");
            }
        },

        init : function(){
            $("input[value=Explicit][type=radio]").click(function(){
                var $elemInput=$(this).parents("div.input");
                $elemInput.children(".paramDerived").hide();
                $elemInput.children("input[type=hidden]").val(
                        $elemInput.find("input.parameters").val()
                    );
                $elemInput.children(".paramExplicit").show();
                TabParams.setDescription($(this).parent().data("description"));
                populateSelectedReport();
            });

            $("input[value=Derived][type=radio]").click(function(){
                var prmName="";
                prmName = $(this).parents(".content_row").find(".prm_name").text();
                var desc="Select an amount and time interval. The "+prmName+" is then calculated based on the run date, less the time interval. (Monthly intervals encompass the first day of the month to the last day of the month.)";
                TabParams.setDescription(desc);
                populateSelectedReport();
                var $elemInput=$(this).parents("div.input");
                $elemInput.children(".paramDerived").show();
                $elemInput.children(".paramExplicit").hide();
                TabParams.setDerivedParams($(this));
            });

            $("input[type=text].quantity").keydown(function(event){
                if ( event.keyCode == 46 || event.keyCode == 8 ) {

                } else {
                    // Ensure that it is a number and stop the keypress
                    if (event.keyCode < 48 || event.keyCode > 57 ) {
                        event.preventDefault();
                    }
                }
            }).keyup(function(){
                TabParams.setDerivedParams($(this));
                 $(this).parents("div.input").find(".calculatedDate").text(
                    $.datepicker.formatDate('mm/dd/yy',getDateBefore(
                            $("#schedulerFooter .schedulerDateFooter").text(),
                            $(this).val(),$(this).next().val()))
                );
                populateSelectedReport();
            });
            $("select.interval").change(function(){
                TabParams.setDerivedParams($(this));
                $(this).parents("div.input").find(".calculatedDate").text(
                    $.datepicker.formatDate('mm/dd/yy',getDateBefore(
                            $("#schedulerFooter .schedulerDateFooter").text(),
                            $(this).prev().val(),$(this).val()))
                );
                populateSelectedReport();
            });
        }
    };

    function populateSelectedReport(){
        $("#selectedReportScheduler .selectedReportScheduleText").text($("#schedulerFooter").text());
        $(".rundate").text($("#schedulerFooter .schedulerDateFooter").text());
        $("div.input select.interval").each(function(){
            $(this).parents("div.input").find(".calculatedDate").text(
                    $.datepicker.formatDate('mm/dd/yy',getDateBefore(
                        $("#schedulerFooter .schedulerDateFooter").text(),
                        $(this).prev().val(),$(this).val())));
        });
        setParams();
    }

	function gotoSubmit(elem, win) {
		if (win == 'reportDefinition'){
            var reportingForm=$('#reporting_form').get(0);
			reportingForm.action = $('#formAction').val() + '&tab_selected='+$("#tabs").tabs( "option", "selected");

			if (elem.className=='button'){
				reportingForm.action += '&sButton='+elem.id;
			}
			if(elem.value == 'Cancel'){
				reportingForm.action += '&sWindow=reportManager';
			}
			else{
				reportingForm.action += '&sWindow=reportDefinition';
			}
            reportingForm.action += '&isDefaultAction=true';
            reportingForm.action += '&nextFireDate='+$("#schedulerFooter .schedulerDateFooter").text();
            reportingForm.action += '&isSchedulerVisible='+isSchedulerVisible;
			if (elem.className=="taglib-icon" || elem.className=="portlet-icon-back"){
				reportingForm.action += '&maximize=true';
			}
			$('#reporting_form').removeAttr("target");
			if ($('#outputFormats').get(0).value == 'HTML' && elem.id == 'viewBtn'){
				$('#reporting_form').attr("target", "_blank");
			}
			else{
				loadingMask('reporting_form');
				$("#loadingMask").parent().css('display',"block");
			}
			reportingForm.submit();
		}
		if (win == 'reportManager'){
            var completedReportName="";
            var $elem=$(elem);
            var reportingManagerForm = $("#report_manager").get(0);
            if(elem.id=="viewCompletedReportBtn" || elem.id=="deleteCompletedReportBtn"){
                completedReportName=$elem.data('completedreportname');
            }
			if (elem.id == 'runNowBtn' || elem.id == 'viewCompletedReportBtn' || elem.id == 'deleteCompletedReportBtn' || elem.id == 'deleteBtn' || elem.id == 'viewMyReportBtn' || elem.id == 'deleteMyReportBtn' || elem.id=='maximPortlet' || elem.id=='minimPortlet'){
				reportingManagerForm.action = $('#formAction').val() + '&sWindow=reportManager';
			}
			else{
				reportingManagerForm.action = $('#formAction').val() + '&sWindow=reportDefinition';
			}
		    reportingManagerForm.action += '&isDefaultAction=true';
            if (elem.id == 'viewCompletedReportBtn' || elem.id == 'deleteCompletedReportBtn'){
                reportingManagerForm.action += '&completedReportName='+completedReportName;
            }
			reportingManagerForm.action += '&sReportId='+selectedReportId;
			if (elem.className=='button'){
				reportingManagerForm.action +='&sButton='+elem.id;
			}
			if (elem.className=="taglib-icon" || elem.className=="portlet-icon-back"){
				reportingManagerForm.action += '&maximize=true';
			}
			if ((selectedReportFrm == 'HTML' && elem.id == 'runNowBtn') || (elem.id == 'viewCompletedReportBtn' && completedReportFrm == 'HTML')){
				$('#report_manager').attr("target", "_blank");
			}
			else{
				loadingMask('report_manager');
				$("#loadingMask").parent().css('display',"block");
				$('#report_manager').removeAttr("target");
			}
			reportingManagerForm.submit();
		}
	};

	function loadingMask(formName){
		var width=$("#"+formName)[0].offsetWidth;
		var height=$("#"+formName)[0].offsetHeight;
		$("#loadingMask")
                .css('width',width)
                .css('height',height)
        .next()
                .css('top',Math.round(height/2)-20)
                .css('left',Math.round(width/2)-30);
	}

	function preConfig(formName,action, helpUrl){
		var preload_image = new Image(25,25);
		preload_image.src="/reporting-web/css/images/loading_indicator.gif";
        var helpButton = '<div id="helpButton"><img onclick="javascript:onHelp(\''+helpUrl+'\');" '+
            'onmouseover="this.src=&quot;/reporting-web/images/questionMarkRed.png&quot;" '+
            'onmouseout="this.src=&quot;/reporting-web/images/questionMarkStandard.png&quot;" '+
            'onmouseup="this.src=&quot;/reporting-web/images/questionMarkStandard.png&quot;" '+
            'src="/reporting-web/images/questionMarkStandard.png" id="help_circle"></div>';
        $('[id^=portlet-topper-toolbar_reporting_portlet_WAR_reportingweb]').prepend(helpButton);

		var maxBack=$('[id^=portlet-topper-toolbar_reporting_portlet_WAR_reportingweb] > .portlet-icon-back');
		maxBack.removeAttr('href');
		maxBack.css('cursor','pointer');
		maxBack.attr('id','minimPortlet');
		maxBack.click(function(){gotoSubmit(maxBack[0], action)});

		var innerHtml='<span class="taglib-icon" id="_reporting_portlet_WAR_reportingweb_INSTANCE_F3Fb_rpbm" style="cursor: pointer; "> <img class="icon" src="/html/themes/classic/images/spacer.png" alt="Maximize" title="Maximize" style="background-image: url(\'/html/themes/classic/images/portlet/.sprite.png\'); background-position: 50% -112px; background-repeat: no-repeat; height: 16px; width: 16px;" id="aui-3-2-0PR1-1899"> </span>'
		var max=$('[id^=portlet-topper-toolbar_reporting_portlet_WAR_reportingweb] span.portlet-maximize a.taglib-icon');
		max.parent().html(innerHtml);
		max=$('[id^=portlet-topper-toolbar_reporting_portlet_WAR_reportingweb] span.portlet-maximize span.taglib-icon');
		max.removeAttr('href');
		max.css('cursor','pointer');
		max.attr('id','maximPortlet');
		max.click(function(){gotoSubmit(max[0], action)});
	}

	function allignParameters(){
		var max=0;
		$(".prm_name").each(function() {
			if ($(this)[0].offsetWidth>max){
				max=$(this)[0].offsetWidth;
			}
		});
		if (max<=170){
			max=180;
		}else{
			max=max+10;
		}
		$(".prm_name").each(function() {
			$(this).parent().css('width',max+'px');
		});
	}

	function setValue(elem,desc){
		if (elem.attr('type')=='checkbox'){
			elem.attr('checked', desc.split('&v&')[1]=='on');
		}
		else{
			elem.val(desc.split('&v&')[1]);
		}

		elem.focus(function(){
			if (desc.split('&v&')[0] != "null") $("#report_parameter_description").html(desc.split('&v&')[0]); }
		);
		elem.blur( function(){ $("#report_parameter_description").html(''); } );
	};

    function setParams(){
        var str="";
        $("#fragment-4 :input:not(input[type=hidden],:radio,.quantity,select)").each(function() {
            var _this = $(this);
            var addParam = function(_paramName, _paramVal) {
                str += (str!="")?", ":"";
                str += _paramName + ": " + _paramVal;
            };

            if (_this.attr('type') == 'checkbox'){
                addParam(_this.attr('id'),_this.attr('checked'));
            } else {
                if ((_this.attr("paramType")=="date"||_this.attr("paramType")=="timestamp")){
                    var isExact=_this.parents("div.input").find(":radio[value=Explicit]").attr("checked")==true;
                    if (isExact){
                        if (_this.val()!="")
                            addParam("Exact " + _this.attr('id'), _this.val());
                    }else {
                        if(_this.parents("div.input").find(".calculatedDate").text()!="")
                            addParam("Calculated " + _this.attr('id'), _this.parents("div.input").find(".calculatedDate").text());
                    }
                } else {
                    if (_this.attr('value') != "") {
                        addParam(_this.attr('id'), _this.attr('value'));
                    }
                }
            }
        });
        $("#paramsDiv").css("display","block");
        $("#paramList").html(str);
    };

	function onHelp(url) {
		popupWindow = window.open(
			url,'Help','height=350,width=400,left=10,top=10,resizable=yes,scrollbars=yes,toolbar=no,menubar=no,location=no,directories=no,status=yes');
		popupWindow.focus();
		};

    function validateSubmit(frm){
        var valid=false;
        var allowSubmit=true;
        $("#fragment-4 :input").each(function() {
            if ($(this).attr('type') == 'checkbox')
                return true;
            else {
                if (jQuery.trim($(this).attr('value'))==""){

                }else{
                    var type = $(this).attr('paramType');
                    switch (type){
                        case 'byte':
                            var patt = '^-?[0-9]{1,3}$';
                            if($(this).attr('value').match(patt)!=null){
                                valid=$(this).attr('value') >= -128 && $(this).attr('value') <= 127;
                            }
                        break;
                        case 'Short':
                            var patt = '^-?[0-9]{1,5}$';
                            if($(this).attr('value').match(patt)!=null){
                                valid=$(this).attr('value') >= -32768 && $(this).attr('value') <= 32767;
                            }
                        break;
                        case 'time':
                            valid=validateTime($(this).attr('value'));
                        break;
                        case 'number':
                            var patt = '^-?[0-9]{1,}([.]{1}[0-9]{1,}){0,1}$';
                            valid=$(this).attr('value').match(patt)!=null;
                        break;
                        case 'double':
                        case 'float':
                        case 'bigdecimal':
                            valid=validateFloat($(this).attr('value'));
                        break;
                        case 'integer':
                        case 'long':
                            valid=validateInt($(this).attr('value'));
                        break;
                        default:
                            valid=true;
                        break;
                    }
                    if (!valid) {
                        $(this).css('border-color', 'red');
                        allowSubmit=false;
                    }else{
                        $(this).css('border-color', '#4F81BD');
                    }
                }
            }
        });
        if (!allowSubmit){
            $("#tabs").tabs('select', 3);
            alert(ErrorMessages.VALIDATION_ERROR);
        }else{
            if (!ReportDefinition.saveAllowed){
                $("#tabs").tabs('select', 0);
                alert(ErrorMessages.REP_NAME_EXISTS);
                return false;
            }
            if (isSchedulerVisible){
                if(!validateScheduler()){
                    return false;
                }else{
                    if(!Scheduler.Recipients.areRecipientsValid()){
                        $("#tabs").tabs('select', 5);
                        alert("Following emails are invalid: "+Scheduler.Recipients.invalidEmails);
                        return false;
                    }
                    Scheduler.Recipients.insertLoggedUserEmail();
                }
            }
            gotoSubmit(frm, "reportDefinition");
        }
    };
    function validateScheduler(){
        var scheduleDate = $.trim($('#scheduleDate').val().split(" ")[0]);
        var scheduleTime = Date.parse($('#scheduleDate').val()).toString("HH:mm");
        if(Scheduler.Frequency.$itm.val()!='OneTime'&&$("input[value=Explicit][type=radio]:checked").length>0){
            $("#tabs").tabs('select', 3);
            alert(ErrorMessages.CANNOT_USE_EXACT_DATES);
            return false;
        }
        if (Scheduler.Frequency.$itm.val()!="OneTime"){return true}
        if(scheduleDate==""){
            $("#tabs").tabs('select', 5);
            alert(ErrorMessages.SCH_DATE_EMPTY);
            return false;
        }
        if(scheduleTime==""){
            $("#tabs").tabs('select', 5);
            alert(ErrorMessages.SCH_TIME_EMPTY);
            return false;
        }
        if (!validateDate($('#scheduleDate'))){
            $("#tabs").tabs('select', 5);
            alert(ErrorMessages.SCH_DATE_INVALID);
            return false;
        }
        if (!validateTime(scheduleTime)){
            $("#tabs").tabs('select', 5);
            alert(ErrorMessages.SCH_TIME_INVALID);
            return false;
        }
        var today=new Date();
        var todayDate = new Date(today.getFullYear(),today.getMonth(),today.getDate()).getTime();
        var selectedDate = $('#scheduleDate').datepicker("getDate").getTime();
        if(todayDate==selectedDate){
            if(scheduleTime.split(':')[0]>today.getHours()){
                return true;
            }else if (scheduleTime.split(':')[0]<today.getHours()){
                $("#tabs").tabs('select', 5);
                alert(ErrorMessages.SCH_TIME_BEFORE_CURRENT);
                return false;
            }else {
                if (scheduleTime.split(':')[1]<=today.getMinutes()){
                    $("#tabs").tabs('select', 5);
                    alert(ErrorMessages.SCH_TIME_BEFORE_CURRENT);
                    return false;
                }else{
                    return true;
                }
            }
        }else if(todayDate>selectedDate){
            $("#tabs").tabs('select', 5);
            alert(ErrorMessages.SCH_DATE_BEFORE_TODAY);
            return false;
        }else{
            return true;
        }
    }

    function validateTime(val){
        var patt = '^[0-2][0-9]:[0-5][0-9]$';
        return val.match(patt)!=null;
    }

    function validateDate(datepicker){
        var isValid = true;
        try{
            $.datepicker.parseDate(datepicker.datepicker( "option", "dateFormat" ), datepicker.val(), null);
        }
        catch(error){
            isValid = false;
        }
        return isValid;
    };

    function validateInt(value){
        var val= parseInt(value);
        if(val.toString() != value.toString()){
            return false;
        }
        else {
            return true;
        }
    };

    function validateFloat(value){
        var val= parseFloat(value);
        if(val.toString() != value.toString()){
            return false;
        }
        else {
            return true;
        }
    };

    function getDateBefore(sDate, iCount, period){
        var date=new Date(sDate);
        if(period==1){
            return date.addDays(-iCount);
        }else if (period==2){
            return date.addWeeks(-iCount);
        }else if (period==3){
            return date.addMonths(-iCount);
        }
    }